import numpy
from numpy import array, dot, sqrt, arccos, cos, empty
from numpy.linalg import norm

def normalize(vector):
    return vector / norm(vector)

# line_strip must be a list of numpy arrays
def parallel_line_strip(line_strip, offset):
	length = len(line_strip)
	assert length >= 2
	
	result = []

	# take special care for head
	v1 = normalize(line_strip[1] - line_strip[0])
	vm = array((v1[1], -v1[0]))
	p_new = line_strip[0] + vm * offset
	result.append(p_new)

	#middle part
	for i in range(1, length-1):
		p1 = line_strip[i-1]
		p2 = line_strip[i]
		p3 = line_strip[i+1]

		v1 = normalize(p2 - p1)
		v2 = normalize(p3 - p2)
		v1 = array((v1[1], -v1[0]))
		v2 = array((v2[1], -v2[0]))
		vm = normalize(v1 + v2)

		arc = arccos(dot(v2, v1))
		arc /= 2.0
		
		p_new = p2 + vm/cos(arc)*offset
		result.append(p_new)

	# take special care for tail
	v1 = normalize(line_strip[length-1] - line_strip[length-2])
	vm = array((v1[1], -v1[0]))
	p_new = line_strip[length-1] + vm * offset
	result.append(p_new)

	return result

def texture_coords_1d(strip):
	lengths = empty(len(strip), dtype="float")
	lengths[0] = 0.0
	for i in range(1, len(strip)):
		lengths[i] = norm(strip[i]-strip[i-1])
	
	lengths = lengths.cumsum()
	lengths /= lengths[-1]

	return lengths

if __name__ == "__main__":
	strip=[]
	strip.append(array((0,0)))
	strip.append(array((0,1)))
	strip.append(array((1,1)))

	print parallel_line_strip(strip,1.0)
	print texture_coords_1d(strip)

